/**
 * @author zhangqiang
 * @date   17/7/18
 */
import React, { Component } from 'react'
import lrz from 'lrz';
import {connect} from 'react-redux'
import {Toast,Icon, Grid } from 'antd-mobile'
import {
	InputItem,
} from '../../components/home'
import {
	setIdCardImg,
	setInsurance,
	setCarouselImg,  
	exchangeUploadImg
} from  '../../actions/uploadPageActions'

//通用组件
import {Title} from '../../components/common'
import config from '../../config'
import '../../../styles/addInfo.scss';
import common from '../../utils/common'
import style from './index.scss'


class UploadPage extends Component {
	constructor(props) {
	super(props);
	this.imgFileChange = this.imgFileChange.bind(this);
	this.state = {
		imgCache: '',
		isShowTemplate: true,  //上传好的图片

		isShowIdCard: false, //身份证实例
		isShowInsurance: false, //交强险实例

		imgFile: ''
	}
	this.type = this.props.params.type
}

	componentWillMount() {
		common.setViewTitle('上传图片');

		sessionStorage.setItem('addInfoIsCountDown',1) //上传图片返回从新倒计时
		
	}
	componentDidMount() {        
	}		

	toUrl(url) {
		this.context.router.push(url);
	}
	//图片改变时触发上传操作
	imgFileChange(e) {
		this.setState({
			imgFile: e.target.files[0]
		})
		this.compressImage(e.target.files[0], (result) => {
			//this.changeImgAndCallBack(result);
			if(this.type == 'idCard'){
				this.props.dispatch(setIdCardImg(result))
			}else{
				this.props.dispatch(setInsurance(result))
			}
			// this.setState({
			// 	// imgCache: result.file,
			// 	isShowTemplate: false
			// });
		});
	}
	   /**
     * 图片压缩上传
     * @param e 图片资源
     */
    compressImage(files, callBack) {
        try {
            Toast.hide();
            Toast.loading("正在上传", 30);
            let quality = 1;
            if (files.size > 1024 * 100) {
                quality = .5;
            } else {
                quality = .7;
            }
            lrz(files, {
                width: 1024,
                quality: quality
            }).then((rst) => {
				Toast.hide();
				let fileImg = {
					pictureName: rst.origin.name,
					size: rst.file.size,
					file: rst.base64,
					uploadType: '04',
					isShowTemplate: false
				};
                callBack(fileImg);
            }).catch((err) => {
                Toast.fail('上传失败', 2);
            }).always(() => {
				this.refs.uploadCompent.value = ""; //清空文件上传的内容 避免上传同一张照片或是拍照时出现的图片无法展示的bug				
            });
        } catch (e) {
            Toast.fail('上传失败', 2);
            console.log(e);
        }

	}
	
    //改变显示的图片
    changeImgAndCallBack(postData){		
		let that = this;
		console.log('ajax',postData)
		var input = document.querySelector('input[type="file"]');	
		console.log(input)	
		var data = new FormData();
		console.log('formData________________',data)
		console.log('__________________100000000000',input.files[0])
		console.log('__________________1111111111111111',input.files[1])
		console.log('____文档溜',this.state.imgFile)
		//data.append('file', input.files[0])
		data.append('file', this.state.imgFile)
		data.append('uploadType','04')	
		data.append('owner','year')
		fetch(`${config.baseApiUrl}emsc-partner/c/u/upload.ajax`, {
			method: 'POST',
			body:data
		}).then(function(response){
			let resp = response.json();
			resp.then(function (data) {
				console.log(data.body.imageUrl)
				let imageUrl = data.body.imageUrl;
				let fileImg = {
					file: imageUrl,
					uploadType: '04'
				};
				if(that.type == 'idCard'){
					that.props.dispatch(setIdCardImg(fileImg))
				}else{
					that.props.dispatch(setInsurance(fileImg))
				}
			})
		})
		// this.props.dispatch(exchangeUploadImg(postData,(result)=>{
		// 	// if(this.type == 'idCard'){
		// 	// 	this.props.dispatch(setIdCardImg(result))
		// 	// }else{
		// 	// 	this.props.dispatch(setInsurance(result))
		// 	// }
		// }))
	}
	/*
	*  切换身份证mask
	*/
	isShowExample(){
		if(this.type == 'idCard'){
			this.setState({
				isShowIdCard: !this.state.isShowIdCard
			})
		}else{
			this.setState({
				isShowInsurance: !this.state.isShowInsurance
			})
		}
	}
	/*
	*  隐藏身份证mask
	*/
	hideIdCard(){
		this.setState({
			isShowIdCard: false
		})
	}

	/*
	*  隐藏交强险mask
	*/
	hideInsurance(){
		this.setState({
			isShowInsurance: false
		})
	}

	toImgPreview(url){
		this.context.router.push(url);	
		this.props.dispatch(setCarouselImg(url.split('=')[1]))
	}

	render() {
		let file = '';
		console.log(this.props.idCardImg)
		console.log(this.props.insuranceImg)
		if(this.type == 'idCard'){
			file = this.props.idCardImg.file;
		}else{
			file = this.props.insuranceImg.file;
		}

		return (
			<div className={style.upload}>
				{/* 头部-start- */}
				<div className={style.titleNav}>
					<span>请上传清晰的照片，以免办理失败</span>
					<div className={style.btnExample} onClick={(e) => {this.isShowExample()}}>
						<span>查看范例</span>
						<img src="./images/icon_right.png" alt=""/>
					</div>
				</div>
				{/* 头部-end- */}
				<div className={style.btnUpload} style={file != ''?{display: 'none'}:{}}>
					<input ref="uploadCompent" type="file" accept="image/*" onChange={(e) => this.imgFileChange(e)}
					className={style.uploadCompent}
					// onclick={()=>{file.select();document.selection.clear()}}
					/>
					<img className={style.frameLeftTop} src="./images/frame_left_top.png" alt=""/>
					<img className={style.frameLeftBottom} src="./images/frame_left_bottom.png" alt=""/>
					<img className={style.frameRightTop} src="./images/frame_right_top.png" alt=""/>
					<img className={style.frameRightBottom} src="./images/frame_right_bottom.png" alt=""/>
					<div className={style.btnCamera}>
						<img className={style.cameraImg} src="./images/photoTemplate.png" alt=""/>
						<div className={style.cameraText}>						
							<img src="./images/to_add.png" alt=""/>
							<span>
								{
									this.type == 'idCard'?'上传手持身份证照片':'上传交强险保单副本'
								}
							</span>
						</div>
						<div className={style.cameraPrompt}>拍照请将相机方框对准证件的边缘并对好焦</div>

					</div>
				</div>

				{/* 上传图片-start- */}
				<div className={style.imgContainer} onClick={()=>{
					this.toImgPreview(`ImgsCarousel?imgs=${file}&index=0`)
					}}>
					<img src={file}/>
				</div>
				{/* 上传图片-end- */}
				<div style={{height: '.4rem'}}></div>
				<div className={style.btnBox} style = {file.indexOf('http')>-1?{display: 'none'}:{}}>
					<button className={style.submit} onClick={()=>{this.changeImgAndCallBack()}}>立即上传</button>
				</div>

				<div style={{height: '.4rem'}}></div>

				<div className={style.btnBox} style={file != ''?{display: 'block'}:{display: 'none'}}>
					<button className={style.submit}>重新上传</button>
					<input ref="uploadCompent" type="file" accept="image/*" onChange={(e) =>
					 this.imgFileChange(e,()=>{
						// document.querySelector('input[type="file"]').value = ''
						// this.refs.uploadCompent.value='';
						// var input = document.querySelector('input[type="file"]');		
						// var data = new FormData()
						// console.log('formData________________',data)
						// console.log('__________________',input.files[0].name)						
					})}
					className={style.uploadCompent}
					   /> 
				</div>

				{/* 交强险保单实例mask -start- */}
					<div className='alert-bg' onClick={()=>{this.hideInsurance()}} style={this.state.isShowInsurance?{display: 'block'}:{}}>
						<img className={style.policyExample} src="./images/policy_example@2x.png" alt=""/>
					</div>
				{/* 交强险保单实例mask -end- */}
				{/* 身份证实例mask -start- */}
					<div className='alert-bg' onClick={()=>{this.hideIdCard()}} style={this.state.isShowIdCard?{display: 'block'}:{}}>
						<img className={style.policyExample} src="./images/pic-idCard@2x.png" alt=""/>
					</div>
				{/* 身份证实例mask -end- */}				
				
			</div>	
		)
	}
}

//使用context
UploadPage.contextTypes = {
	router: React.PropTypes.object.isRequired
};

UploadPage.defaultProps = {
	insuranceImg: {
		file: ''
	},
	idCardImg: {
		file: ''
	}
};

function mapStateToProps(state) {
    return Object.assign({}, state.uploadPageResult)       
}


export default connect(mapStateToProps)(UploadPage);
